#include "epoller.h"
#include <cassert>
#include <cstdint>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/epoll.h>

Epoller::Epoller(int maxEvent) : epollfd_(epoll_create(512)), events_(maxEvent) {
    // fd: 0 1 2 -> 标准输入 标准输出 标准错误
    assert(epollfd_ >= 0 && events_.size() > 0);
}

Epoller::~Epoller() {
    close(epollfd_);
}

bool Epoller::AddFd(int fd, uint32_t events) {
    if(fd < 0) {
        return false;
    }
    epoll_event ev = {0};
    ev.data.fd = fd;
    ev.events = events;
    return 0 == epoll_ctl(epollfd_, EPOLL_CTL_ADD, fd, &ev);
}

bool Epoller::ModFd(int fd, uint32_t events) {
    if(fd < 0) {
        return false;
    }
    epoll_event ev = {0};
    ev.data.fd = fd;
    ev.events = events;
    return 0 == epoll_ctl(epollfd_, EPOLL_CTL_MOD, fd, &ev);
}

bool Epoller::DelFd(int fd) {
    if(fd < 0) {
        return false;
    }
    epoll_event ev = {0};
    return 0 == epoll_ctl(epollfd_, EPOLL_CTL_DEL, fd, &ev);
}

int Epoller::Wait(int timeoutMs) {
    // 所有的epoll_event关注的事件都是一样的
    return epoll_wait(epollfd_, &events_[0], static_cast<int>(events_.size()), timeoutMs);
}

int Epoller::GetEventFd(size_t i) const {
    assert(i < events_.size() && i >= 0);
    return events_[i].data.fd;
}

uint32_t Epoller::GetEvents(size_t i) const {
    assert(i >= 0 && i < events_.size());
    return events_[i].events;
}